package org.grayrabbit.cms.action.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.grayrabbit.cms.constant.ConfigCode;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.publish.api.Publishable;
import org.grayrabbit.cms.service.site.SiteService;
import org.grayrabbit.cms.service.system.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("timePublishTask")
public class TimePublishTask {

	private static final Logger log = LoggerFactory.getLogger(TimePublishTask.class);

	
	@Autowired
	@Qualifier("publishableImpl")
	private Publishable publishable;
	
	@Autowired
	@Qualifier("siteServiceImpl")
	private SiteService siteService;
	
	@Autowired
	@Qualifier("configServiceImpl")
	private ConfigService configService;
	
	private static int pageSize = 0;;
	private static int pageNum = 0;
	
	public void addSchedule(Date date) {
		initListPageParam();
		Timer timer = new Timer();
		MyTask task  = new MyTask();
		timer.schedule(task, date, 60000*60*24);
		
	}
	
	private void initListPageParam(){
		if(pageSize==0){
			pageSize =(configService.getConfigByAttrKey(ConfigCode.PUBLISH_LIST_PAGE_SIZE)==null
					||configService.getConfigByAttrKey(ConfigCode.PUBLISH_LIST_PAGE_SIZE).getConfigAttrValue()==null)?20:Integer.parseInt(configService.getConfigByAttrKey(ConfigCode.PUBLISH_LIST_PAGE_SIZE).getConfigAttrValue());
			pageNum =(configService.getConfigByAttrKey(ConfigCode.PUBLISH_LIST_PAGE_NUM)==null
					||configService.getConfigByAttrKey(ConfigCode.PUBLISH_LIST_PAGE_NUM).getConfigAttrValue()==null)?20:Integer.parseInt(configService.getConfigByAttrKey(ConfigCode.PUBLISH_LIST_PAGE_NUM).getConfigAttrValue());
		}
	}

	class MyTask extends TimerTask {
		@Override
		public void run() {
			log.info("周期发布定时任务启动");
			List<Site> sites = siteService.findAllUsableSite();
			for(Site site:sites){
				List<String> targets = new ArrayList<String>();
				targets.add(site.getSiteId());
				publishable.publish(site,Publishable.SITE_GEN,Publishable.ALL_PUBLISH, targets, null, "127.0.0.1", true, pageSize, pageNum);
			}
			log.info("周期发布定时任务启动结束");
		}

	}
}
